<?php

namespace app\api\validate;

use think\facade\Cache;
use think\Validate;

class UserValidate extends Validate
{
    protected $rule = [
        'store_id' => 'require|integer',
        'open_id' => 'require',
        'ali_user_id' => 'require',
        'phone'     => 'require|mobile|unique:user_auth,phone',
        'auth_type' => 'require|checkAuth',
        'avatar' => 'requireWith|max:255',
        'nickname' => 'requireWith|max:80',
        'gender' => 'requireWith|in:0,1,2',
        'code'      => 'require|length:6|checkCode',
        'password'  => 'require|regex:^[a-zA-Z\d!@#$%^&*_.]{6,18}$|confirm',
        'old_password'=>'require'
    ];

    protected $message = [
        'phone.require' => '请输入手机号!',
        'auth_type.require' => '非法登录!',
        'phone.mobile' => '手机号不合法!',
        'phone.unique' => '手机号已存在!',
        'store_id.require' => '店铺标识不能为空!',
        'code.require' => '请输入短信验证码!',
        'code.length' => '短信验证码不合法!',
        'password.require' => '请输入密码!',
        'password.regex' => '密码必须在6-18之间必须包含大小写字母/数字/符号任意两者组合',
        'password.confirm' => '两次密码不一致!'
    ];

    public function sceneBindPhone()
    {
        return $this->only(['store_id','phone','code'])->remove('phone','unique');
    }

    public function sceneWjPassword()
    {
        return $this->only(['store_id','phone','password', 'code'])->remove('phone','unique');
    }


    public function sceneModifyPassword()
    {
        return $this->only(['store_id','password', 'code'])->remove('password','confirm');
    }

    public function sceneRegister()
    {
        return $this->only(['phone','store_id','password','code']);
    }

    public function scenePhoneLogin()
    {
        return $this->only(['phone','auth_type','store_id','password'])
                    ->remove('phone','unique')
                     ->remove('password','confirm');
    }

    /**
     * 手机号验证码登录
     */
    public function scenePhoneCodeLogin()
    {
        return $this->only(['phone','code','store_id'])
                    ->remove('phone','unique');
                    //  ->remove('password','confirm');
    }

    public function sceneWxLogin()
    {
        return $this->only(['open_id','auth_type','store_id','nickname','avatar','gender']);
    }


    public function sceneAliLogin()
    {
        return $this->only(['ali_user_id','auth_type','store_id','nickname','avatar','gender']);
    }

    public function sceneSms()
    {
        return $this->only(['store_id','phone'])->remove('phone','unique');
    }

    public function sceneAuthSms()
    {
        return $this->only(['store_id']);
    }

    public function checkAuth($value)
    {
        $arr = ['wx','ali','phone'];

        return in_array($value,$arr) ? true : '非法登录!';
    }

    protected function checkCode($value, $rule, $data)
    {
       $key = $data['phone'].'-'.$data['store_id'];
       $code = Cache::get($key);
    //    return  true;
       return $value == $code ? true : '短信验证码错误';
    }
}